<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\index\controller;
use think\Controller;
use think\Db;

class Ali extends Controller
{
    protected $config = array(
        'app_id' => '202100',
        'ali_public' => '',
        'public_key' => "",
        'private_key' => '',
        'notify_url'  => 'http://panson.xuanwumobile.com/index/Ali/huidiao', // 接收支付状态的连接
        'return_url'  => 'http://panson.xuanwumobile.com/index/Index/index', // 接收支付状态的连接

    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {

    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam()
    {
        $no = time() . rand(100000,999999);
        $school = $_POST['school'];
        $grade = $_POST['grade'];
        $class = $_POST['class'];
        $name = $_POST['name'];
        $sex = $_POST['sex'];
        $idcard = $_POST['idcard'];
        $money = $_POST['money'];
        $type = $_POST['type'];
        $order = [
            'orderno' => $no,
            'school' => $school,
            'grade' => $grade,
            'class' => $class,
            'name' => $name,
            'sex' => $sex,
            'idcard' => $idcard,
            'money' => $money,
            'time' => date('Y-m-d H:i:s'),
            'type' => $type
        ];
        $id = $_POST['id'];
        $data = Db::table('up_offline_schcode')
            ->where('id', $id)
            ->find();
        if(empty($data)){
            return 3;
        }
        if($data['status'] != 1){
            return 3;
        }
        //-------------------------------------------------------------------------
        if($data['usetype'] == 3){
            $order['height'] = $_POST['height'];
            $order['weight'] = $_POST['weight'];
            $order['size'] = $_POST['size'];
            $order['sw_j'] = $_POST['sw_j'];
            $order['sw_x'] = $_POST['sw_x'];
            $order['sw_y'] = $_POST['sw_y'];
            $order['sw_t'] = $_POST['sw_t'];
            $order['sw_b'] = $_POST['sw_b'];
            $order['sw_k'] = $_POST['sw_k'];
            $order['xiguan'] = $_POST['xiguan'];
            $order['phone'] = $_POST['phone'];
        }
        $order['fromtype'] = $data['usetype'];
        //-------------------------------------------------------------------------
        $res = Db::table('up_offline_order')->insert($order);
        if($res){
            import('alipay.aop.AopClient', EXTEND_PATH);
            import('alipay.aop.request.AlipayTradeWapPayRequest', EXTEND_PATH);
            $aop = new \AopClient ();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $this->config['app_id'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $aop->apiVersion = '1.0';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $aop->signType='RSA2';
            $request = new \AlipayTradeWapPayRequest ();
            $request->setNotifyUrl($this->config['notify_url']);
//        $request->setReturnUrl($this->config['return_url']);
            $request->setBizContent("{" .
                "\"body\":\"派逊服饰线下支付\"," .
                "\"subject\":派逊服饰," .
                "\"out_trade_no\":\"$no\"," .
                "\"timeout_express\":\"90m\"," .
                "\"total_amount\":\"$money\"," .
                "\"product_code\":\"QUICK_WAP_WAY\"" .
                "  }");
            $result = $aop->pageExecute ( $request);
            echo $result;
        }else{
            return 2;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $backno = $getInfo['backno'];//订单号
                Db::table('up_offline_order')->where('orderno',$num)->update([
                    'status' => 2,
                    'backno' => $backno,
                    'time' => date('Y-m-d H:i:s')
                ]);
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}